package periodTask

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"reflect"
	"time"
)

type periodTaskScheduler struct {
}

func (e *periodTaskScheduler) executeOnceTask() {
	periodTaskList := manager.queryOnceTask()
	for _, periodTask := range periodTaskList {
		e.execute(periodTask)
	}
}

func (e *periodTaskScheduler) executeShareTask() {
	periodTaskList := manager.queryShareTask(time.Now().UnixMilli())
	for key, task := range periodTaskList {
		e.execute(task)
		manager.updateShareTask(key, time.Now().UnixMilli())
	}
}

func (e *periodTaskScheduler) execute(task IPeriodTask) {
	// 定义一个函数级的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			typ := reflect.TypeOf(task).Elem()
			commLogger.Console.Error(fmt.Sprintf("execute() 捕获到异常:%v,%v", typ.Name(), r))
		}
	}()

	task.Execute()
}

func (e *periodTaskScheduler) scheduler() {
	for true {
		time.Sleep(1 * time.Second)

		e.executeOnceTask()
		e.executeShareTask()
	}
}
